package erfgame.core.world.terrain.insertion;

import java.awt.Point;
import java.awt.Rectangle;


public class DefaultSurfaceInsertionComparer 
	implements SurfaceInsertionComparer {
	
	public static final DefaultSurfaceInsertionComparer INSTANCE = new DefaultSurfaceInsertionComparer();

	public int compare(SurfaceInsertion i1, SurfaceInsertion i2) {
		Rectangle b1 = i1.getBounds();
		Rectangle b2 = i2.getBounds();
		if( i1 instanceof SurfaceTerrainImageInsertion && i2 instanceof SurfaceTerrainImageInsertion ) {
			return ORDER_DONT_CARE;
		} else {
			Rectangle intersection = b1.intersection( b2 );
			if( intersection.width > 0 && intersection.height > 0 ) {
				int d1;
				int d2;
				if( i1 instanceof SurfaceRendererInsertion  && i2 instanceof SurfaceRendererInsertion ) {
					SurfaceRendererInsertion r1 = (SurfaceRendererInsertion)i1;
					SurfaceRendererInsertion r2 = (SurfaceRendererInsertion)i2;
					d1 = r1.getDepth();
					d2 = r2.getDepth();
				} else {
					if( i1 instanceof SurfaceRendererInsertion ) {
						SurfaceRendererInsertion sr1 = (SurfaceRendererInsertion)i1;
						Point p1 = sr1.getRenderer().getGrabPoint();
						int x1 = b1.x + p1.x - sr1.getXOff();
						int y1 = b1.y + p1.y - sr1.getYOff();
						if( intersection.contains( x1, y1 ) ) {
							Point p = new Point( x1, y1 );
							d1 = i1.getDepth(p);
							d2 = i2.getDepth(p);
							if( d1 < 0 ) {
								d1 = i1.getDepth(intersection);
							}
							if( d2 < 0 ) {
								d2 = i2.getDepth(intersection);
							}
						} else {
							d1 = i1.getDepth(intersection);
							d2 = i2.getDepth(intersection);
						}
					} else if( i2 instanceof SurfaceRendererInsertion ) {
						SurfaceRendererInsertion sr2 = (SurfaceRendererInsertion)i2;
						Point p2 = sr2.getRenderer().getGrabPoint();
						int x2 = b2.x + p2.x - sr2.getXOff();
						int y2 = b2.y + p2.y - sr2.getYOff();
						if( intersection.contains( x2, y2 ) ) {
							Point p = new Point( x2, y2 );
							d1 = i1.getDepth(p);
							d2 = i2.getDepth(p);
							if( d1 < 0 ) {
								d1 = i1.getDepth(intersection);
							} 
							if( d2 < 0 ) {
								d2 = i2.getDepth(intersection);
							} 
						} else {
							d1 = i1.getDepth(intersection);
							d2 = i2.getDepth(intersection);
						}
					} else {
						d1 = i1.getDepth(intersection);
						d2 = i2.getDepth(intersection);
					}
				}
				if( d1 >= 0 && d2 >= 0 ) {
					if( d1 > d2 ) {
						return ORDER_IN_FRONT;
					} else if( d1 == d2 ) {
						return ORDER_DONT_CARE;
					} else {
						return ORDER_BEHIND;
					}
				} else { 
					return ORDER_DONT_CARE;
				}
			} else {
				return ORDER_DONT_CARE;
			}
		}
	}
}
